package com.runmonk.core.study.concurrent.thread_test;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Exchanger是一个线程交换者，用于线程间协作的工具类，Exchanger用于线程间的数据交换
 * 它提供一个同步点，在这个同步点进行数据交换
 *
 * @name：ExchangerTest
 * @since：2019/10/4 9:13 AM
 * @author：runmonk
 */
public class ExchangerTest {
    private  static  final Exchanger<String> exchanger=new Exchanger<String>();

    //创建一个固定2个线程的线程池
    private static ExecutorService threadPool=Executors.newFixedThreadPool(2);

    public static void main(String[] args) {
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                String A="银行流水A";
                try {
                    exchanger.exchange(A);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        threadPool.execute(new Runnable() {
            @Override
            public void run() {

                try {
                    String B="银行流水B";
                    String A=exchanger.exchange(B);
                    System.out.println("A和B的数据是否一致："+A.equals(B)+"A录入的是------>>>："+A+",B录入的是------>>>>："+B);
                    exchanger.exchange(A);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        threadPool.shutdown();//关闭线程池
    }
}
